<template>
  <div id="LabTMLBDict">
    <Breadcrumb content="批次审核" v-if="showBreadCrumbTag === true" />
    <GoBack :content="'批次审核'" v-if="showBreadCrumbTag === false" @closeDrawer="closeDrawer" :backUrl="url"></GoBack>
    <div class="bodyContent">
      <Splitpanes class="area">
        <Pane size="20">
          <el-scrollbar style="height: 100%">
            <vxe-form ref="formRef" :data="formData" title-width="80" class-name="padding-sm width-100-percentage">
              <vxe-form-item title="报告单元" class-name="width-100-percentage">
                <template #default>
                  <SelectWorkGroupAll ref="selectWorkGroupRef" :url="'/api/rptGroup/findRptGroup'" :inputWidth="'100%'" @fatherMethod="searchWklt" :isShowAll="true" :isClear="true"></SelectWorkGroupAll>
                </template>
              </vxe-form-item>
              <vxe-form-item title="标本日期[起]" class-name="width-100-percentage">
                <template #default="{ data }">
                  <el-date-picker v-model="data.scheduleDateBegin" :value-format="'YYYY-MM-DD HH:mm:ss'" type="datetime" placeholder="标本日期[起]" :popper-style="{zIndex:9999999}" :tabindex="999000" :shortcuts="shortcuts" style="width: 100%" @change="selectWtIdChange" />
                </template>
              </vxe-form-item>
              <vxe-form-item title="标本日期[止]" class-name="width-100-percentage">
                <template #default="{ data }">
                  <el-date-picker v-model="data.scheduleDateEnd" :value-format="'YYYY-MM-DD HH:mm:ss'" type="datetime" placeholder="标本日期[止]" :popper-style="{zIndex:9999999}" :tabindex="999000" :shortcuts="shortcuts" style="width: 100%" @change="selectWtIdChange" />
                </template>
              </vxe-form-item>
              <vxe-form-item title="标本号" class-name="width-100-percentage">
                <template #default="{ data }">
                  <vxe-input class="enterNextInputFlag" type="text" v-model="data.sampleNo" placeholder="请输入1,2,5-8等格式" clearable class-name="width-100-percentage" style="margin-bottom: 5px" @blur="selectWtIdChange"></vxe-input>
                </template>
              </vxe-form-item>
              <vxe-form-item title="病人类型" class-name="width-100-percentage">
                <template #default="{ data }">
                  <VxePulldownMultiSelection childIndex="visitType" url="/api/sys/basDictDetail/findDictDetailList" :dataObj="{ code: 'PATTYPE' }" @confirmClick="(data) => confirmList(data, 'visitType')" :tableColumn="[
                            { field: 'name', title: '名称' },
                            { field: 'code', title: '编号' }
                          ]" :displayTexts="['name']" :displayTextObj="data.visitTypeName" :dicValues="data.visitTypes" includeVal="commonId" />
                </template>
              </vxe-form-item>
              <vxe-form-item title="科室" class-name="width-100-percentage">
                <template #default="{ data }">
                  <VxePulldownMultiSelection childIndex="dep" url="/api/sys/findDepartmentList" :dataObj="{ orgId: store.userInfo.orgId }" @confirmClick="(data) => confirmList(data, 'dep')" :tableColumn="[
                            { field: 'code', title: '编号' },
                            { field: 'name', title: '名称' }
                          ]" :displayTexts="['name']" :displayTextObj="data.depName" :dicValues="data.deps" includeVal="id" />
                </template>
              </vxe-form-item>

              <vxe-form-item field="registrantName" title="检验医师" class-name="width-100-percentage">
                <template #default="{ data }">
                  <VxePulldownMultiSelection childIndex="registrant" :url="'api/user/getUserInfoList?skipCount=0&maxResultCount=200'" @confirmClick="(data) => confirmList(data, 'registrant')" :tableColumn="[
                            { field: 'username', title: '编号' },
                            { field: 'realname', title: '名称' }
                          ]" :displayTexts="['realname']" :displayTextObj="data.registrantName" :dicValues="data.registrants" includeVal="id" />
                </template>
              </vxe-form-item>

              <vxe-form-item title="审核标志" class-name="width-100-percentage">
                <vxe-radio-group v-model="formData.isReviewed" @change="selectWtIdChange">
                  <vxe-radio-button :label="null">全部</vxe-radio-button>
                  <vxe-radio-button :label="1">已审核</vxe-radio-button>
                  <vxe-radio-button :label="0">未审核</vxe-radio-button>
                </vxe-radio-group>
              </vxe-form-item>
              <vxe-form-item title="打印标志" class-name="width-100-percentage">
                <vxe-radio-group v-model="formData.isPrinted" @change="selectWtIdChange">
                  <vxe-radio-button :label="null">全部</vxe-radio-button>
                  <vxe-radio-button :label="1">已打印</vxe-radio-button>
                  <vxe-radio-button :label="0">未打印</vxe-radio-button>
                </vxe-radio-group>
              </vxe-form-item>

              <vxe-form-item title="筛选条件" class-name="width-100-percentage">
                <vxe-checkbox v-model="formData.isFilterNoResult" @change="selectWtIdChange">不处理无检验结果样本</vxe-checkbox>
                <br />
                <vxe-checkbox v-model="formData.isFilterNoSpecCode" @change="selectWtIdChange">不处理无条码号样本</vxe-checkbox>
                <br />
                <vxe-checkbox v-model="formData.isFilterNoPatName" @change="selectWtIdChange">不处理无病人姓名样本</vxe-checkbox>
              </vxe-form-item>

              <vxe-form-item title-width="0" class-name="width-100-percentage">
                <template #default>
                  <div class="width-100-percentage">
                    <!-- <vxe-button type="text" content="重置条件" class="button-blue" @click="resetForm"></vxe-button> -->
                    <vxe-button status="primary" content="查询数据" @click="selectWtIdChange" class="searchDataBtn"></vxe-button>
                  </div>
                </template>
              </vxe-form-item>
            </vxe-form>
          </el-scrollbar>

          <!-- 中间表格+右侧表格组件  -->
        </Pane>
        <pane size="80">
          <WkltResult ref="wLResultRef" :triggerSource="'1'" />
        </pane>
      </Splitpanes>
    </div>
  </div>
</template>
<script setup lang="ts">
// 引入组件区 ==========
import Breadcrumb from '@/components/Breadcrumb.vue'; //面包屑
import GoBack from '@/components/GoBack.vue'; //返回组件
import { Splitpanes, Pane } from 'splitpanes';
import { reactive, ref, getCurrentInstance, onMounted, watch } from 'vue';
import { IsEmpty, formatDateTime } from '@/utils/common.ts';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage';
import SelectWorkGroup from '../lab_bus/components/SelectWorkGroup.vue'; //工作组引入下拉组件
import SelectWorkGroupAll from '../lab_bus/components/SelectWorkGroupAll.vue'; //报告单元默认全部引入下拉组件
import VxePulldownMultiSelection from '@/components/VxePulldownMultiSelection.vue';

import WkltResult from './WkltResult.vue'; //中间表格+右侧表格组件
import { GetRptGroupOptions } from '@/utils/SysOptionsHelper';
import { AppStore } from '@/stores/store';
let store = AppStore();
// 全局变量定义区 ==========
defineExpose({
  init
});

const shortcuts = [
  {
    text: '今天',
    value: new Date()
  },
  {
    text: '昨天',
    value: () => {
      const date = new Date();
      date.setDate(date.getDate() - 1);
      return date;
    }
  },
  {
    text: '一周前',
    value: () => {
      const date = new Date();
      date.setDate(date.getDate() - 7);
      return date;
    }
  }
];
const orgList = store.userInfo.orgList;

onMounted(() => {
  getDictPatTypeList();
  getSampleType();
});

let showBreadCrumbTag = ref(true); //当为true时显示的是普通面包屑 false显示的是返回组件
let url = ref(''); //抽屉要返回的路由地址
function init(row: any, row2: any) {
  // console.log('传过来抽屉前的那个路由',row,row2)
  // showBreadCrumbTag.value = row
  url.value = row;
  showBreadCrumbTag.value = !row2;
  // console.log('要跳回去的路由',url.value)
}

// 关闭抽屉
function closeDrawer() {
  showBreadCrumbTag.value = true; //恢复成面包屑
  proxy.$emit('closeDrawer');
}

let { proxy }: any = getCurrentInstance();
let selectWorkGroupRef = ref(null);
const formRef = ref(); //表单ref标记
//病人类型
const visitTypeList: any[] = reactive([]);
//样本类型
const specTypeList = reactive([]);

// 表单绑定的数据类型限制
interface FormDataVO {
  orgId: string /*组织id*/;
  orgName: string /*组织名称*/;
  sampleNo: string /*标本号*/;
  isFilterNoPatName: boolean /*无病人姓名样本*/;
  isFilterNoResult: boolean /*无检验结果样本*/;
  isFilterNoSpecCode: boolean /*无条码号样本*/;
  isPrinted: Number /*审核标志*/;
  isReviewed: Number /*打印标志*/;
  skipCount: Number /*样本类型最小数*/;
  maxResultCount: Number /*样本类型最大数*/;
  scheduleDateBegin: string /*标本日期开始时间*/;
  scheduleDateEnd: string;
  specTypeIds: [] /*样本类型*/;
  visitTypeName: string;
  visitTypes: [] /*病人类型*/;
  depName: string;
  deps: [] /*科室*/;
  registrantName: string;
  registrants: [] /*科室*/;
  wtId: string /*工作组id*/;
}
// 表单绑定的数据
let formData = reactive<FormDataVO>({
  /*  orgId: store.userInfo.orgId,
  orgName: store.userInfo.orgName,*/
  orgId: '',
  orgName: '',
  sampleNo: '',
  isFilterNoPatName: false,
  isFilterNoResult: false,
  isFilterNoSpecCode: false,
  isPrinted: null,
  isReviewed: 0,
  maxResultCount: 0,
  scheduleDateBegin: formatDateTime(new Date().valueOf() - 0 * 24 * 60 * 60 * 1000, 'yyyy-MM-dd 00:00:00'),
  scheduleDateEnd: formatDateTime(new Date().valueOf(), 'yyyy-MM-dd 23:59:59'),
  skipCount: 0,
  specTypeIds: [],
  visitTypeName: '',
  visitTypes: [],
  depName: '',
  deps: [],
  registrantName: '',
  registrants: [],
  wtId: ''
});
let wLResultRef = ref(null); //引用中间表格+右侧表格组件ref
let defaultProps = {
  children: 'children',
  label: 'name'
};
// 方法定义区 =============
/*onMounted(() => {
  selectWtIdChange(); // 左侧表单查询按钮
});*/

// 接收子组件传过来的选中的id(选择的那个工作组的id)
function searchWklt(propValue: any) {
  GetRptGroupOptions(propValue.value);
  formData.wtId = propValue.value;
  selectWtIdChange();
}

function handleOrgNodeClick(data: any) {
  formData.orgId = data.id;
  formData.orgName = data.name;
  selectWtIdChange();
}

// 重置表单
function resetForm() {
  formData.sampleNo = '';
  formData.isFilterNoPatName = false;
  formData.isFilterNoResult = false;
  formData.isFilterNoSpecCode = false;
  formData.isPrinted = 0;
  formData.isReviewed = 0;
  formData.maxResultCount = 0;
  formData.scheduleDate = '';
  formData.skipCount = 0;
  formData.specTypeIds = [];
  formData.visitTypes = [];
  formData.deps = [];
  //selectWorkGroupRef.value?.resetSelectedVal(); //重置选中的工作组
}

// 查询按钮
function selectWtIdChange() {
  wLResultRef.value?.getWklt(formData);
}
//获取病人类型数据字典
function getDictPatTypeList() {
  visitTypeList.length = 0;
  const url = '/api/sys/basDictDetail/findDictDetailList';
  proxy.$http
    .get(url, { params: { code: 'PATTYPE' } })
    .then((res: any) => {
      //patTypeList.push(...res.data);
      Object.assign(visitTypeList, res.data);
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
    });
}
//获取样本类型
function getSampleType() {
  specTypeList.length = 0;
  const url = '/api/lab/labSampleType/findSampleTypeList';
  proxy.$http
    .get(url)
    .then((res: any) => {
      //patTypeList.push(...res.data);
      Object.assign(specTypeList, res.data);
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
    });
}

function confirmList(data, keyName) {
  formData[keyName + 's'] = [];
  formData[keyName + 'Ids'] = [];
  formData[keyName + 'Name'] = '';
  if (IsEmpty(data.aimKeys) || data.aimKeys.length === 0) {
    const arr = data.arr;
    formData[keyName + 's'] = arr;
    if (arr.length !== 0) {
      arr.forEach((item) => {
        formData[keyName + 'Ids'].push(item.id);
        if (item.name) {
          formData[keyName + 'Name'] += item.name + ',';
        } else if (item[keyName + 'Name']) {
          formData[keyName + 'Name'] += item[keyName + 'Name'] + ',';
        } else {
          formData[keyName + 'Name'] += item.realname + ',';
        }
      });

      if (formData[keyName + 'Name'] && formData[keyName + 'Name'].trim()) {
        formData[keyName + 'Name'] = formData[keyName + 'Name'].slice(0, -1);
      }
    }
  } else {
    data.arr.forEach((item) => {
      data.aimKeys.forEach((val) => {
        formData[val.targetField + 's'].push(item);
        formData[val.targetField + 'Ids'].push(item[val.targetField + 'Id']);
        formData[val.targetField + 'Name'] += item[val.targetField].name + ',';
      });
    });
  }
}
</script>
<style lang="scss" scoped>
#LabTMLBDict {
  width: 100%;
  height: 100%;
  .bodyContent {
    // 面包屑40px  上下间距10px
    height: calc(100% - 60px);
    .area {
      background-color: $base-white;
      height: 100%;
      :deep(.el-scrollbar__view) {
        height: 100%;
        .vxe-form {
          height: 100%;
          .vxe-checkbox {
            margin: 8px 10px 0 0;
          }
          .searchDataBtn {
            margin: 10px 0 0 80px;
            border-radius: 5px;
          }
        }
      }
    }
  }
}
</style>
